package com.egu.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.egu.mapper.UserRoleMapper;
import com.egu.model.User;
import com.egu.model.UserRole;
import com.egu.model.UserRoleExample;
import com.egu.model.UserRoleExample.Criteria;
import com.egu.service.UserRoleService;
import com.egu.vo.PageParam;
import com.egu.vo.RequestPageVo;
import com.egu.vo.RequestResultVo;

@Service
public class UserRoleServiceImpl implements UserRoleService {
	@Autowired
	UserRoleMapper userRoleMapper;

	@Override
	public RequestResultVo<List<UserRole>> getAllList() {
		UserRoleExample example = new UserRoleExample();
		example.createCriteria().andIsUsedEqualTo("1");
		List<UserRole> list = userRoleMapper.selectByExample(example);
		return RequestResultVo.success(list);
	}

	@Override
	@Transactional
	public RequestResultVo<UserRole> saveOrUpdate(UserRole userRole) {
		if (userRole.getId() == null) {
			userRoleMapper.insertSelective(userRole);
		} else {
			userRoleMapper.updateByPrimaryKeySelective(userRole);
		}
		return RequestResultVo.success();
	}

	@Override
	@Transactional
	public RequestResultVo<UserRole> deleteDataById(Integer id) {
		UserRole userRole = new UserRole();
		userRole.setId(id);
		userRole.setIsUsed("0");
		try {
			userRoleMapper.updateByPrimaryKeySelective(userRole);
		} catch (Exception e) {
			return RequestResultVo.error("数据库操作异常");
		}
		return RequestResultVo.success();
	}

	@Override
	public RequestPageVo<UserRole> getList(PageParam param, UserRole userRole) {
		RequestPageVo<UserRole> result = new RequestPageVo<UserRole>();
		UserRoleExample example = new UserRoleExample();
		Criteria criteria = example.createCriteria();
		criteria.andIsUsedEqualTo("1");
		if (StringUtils.isNotBlank(userRole.getRoleName())) {
			criteria.andRoleNameLike("%"+userRole.getRoleName()+"%");
		}
		int count = (int) userRoleMapper.countByExample(example);
		if (count > 0) {
			example.setStartPage(param.getOffset());
			example.setPageSize(param.getLimit());
			List<UserRole> list = userRoleMapper.selectByExample(example);
			result.setRows(list);
			result.setTotal(count);
		}
		return result;
	}

	@Override
	public UserRole getUserRoleByCurrentUser(User user) {
		UserRole userRole = userRoleMapper.selectByPrimaryKey(user.getRoleId());
		return userRole;
	}

}
